package com.bawei.common.mvi

import android.os.Bundle
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * 作者：Jason
 * 日期：2023/11/16
 * 描述：MVI基类Activity
 */
abstract class BaseMviActivity<T : ViewDataBinding> : BaseActivity<T>() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //注册EventBus
        EventBus.getDefault().register(this)
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public fun receiveEvent(event: BaseEvent) {
        if (event != null && event.target == this::class.java.simpleName) {
            handEvent(event)
        }
    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }


    override fun initData() {
        lifecycleScope.launch {
            sendViewIntent()
        }
    }

    override fun updateUI() {
        lifecycleScope.launch {
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                collectUIState()
            }
        }
    }

    //子类负责具体的实现
    open fun handEvent(event: BaseEvent) {

    }

    //收集ViewModel中UI状态
    open suspend fun collectUIState() {

    }

    //发送View层的意图
    open suspend fun sendViewIntent() {

    }
}